package com.sayimo.maker.commons.push.netty;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.sayimo.maker.commons.push.netty.msg.BaseMsg;
import com.sayimo.maker.commons.push.netty.msg.LoginMsg;
import com.sayimo.maker.commons.push.netty.msg.MsgType;
import com.sayimo.maker.commons.push.netty.msg.PingMsg;
import com.sayimo.maker.commons.push.netty.msg.PushMsg;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.ReferenceCountUtil;

/**
 * @Project: schoolmallapi
 * @ClassName: NettyServerHandler
 * @Description: 客户端消息处理
 * @author:	chenpy
 * @date:	2016年11月1日
 * @version 1.0.0
 */
@Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<BaseMsg> {
	
	private static Logger logger = LogManager.getLogger(NettyServerHandler.class);

	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// channel失效，从Map中移除
		NettyContextChannelMap.remove((SocketChannel) ctx.channel());
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		logger.info("服务器端出现异常！");
	}

	// 这里是从客户端过来的消息
	protected void messageReceived(ChannelHandlerContext channelHandlerContext, BaseMsg baseMsg) throws Exception {
		
		if (MsgType.LOGIN.equals(baseMsg.getType())) {
			LoginMsg loginMsg = (LoginMsg) baseMsg;
			if (NettyContextChannelMap.get(loginMsg.getPhoneNum()) == null) {
				// 登录成功,把channel存到服务端的map中
				NettyContextChannelMap.add(loginMsg.getPhoneNum(), (SocketChannel) channelHandlerContext.channel());
				logger.info("client" + loginMsg.getPhoneNum() + " 登录成功");
			}
		} else {
			if (NettyContextChannelMap.get(baseMsg.getPhoneNum()) == null) {
				// 说明未登录，或者连接断了，服务器向客户端发起登录请求，让客户端重新登录
				LoginMsg loginMsg = new LoginMsg();
				channelHandlerContext.channel().writeAndFlush(loginMsg);
			}
		}
		
		switch (baseMsg.getType()) {
			case PING:
				PingMsg pingMsg = (PingMsg) baseMsg;
				PingMsg replyPing = new PingMsg();
				NettyContextChannelMap.get(pingMsg.getPhoneNum()).writeAndFlush(replyPing);
				logger.info("收到PING类型");
				break;
			case LOGIN:
				break;
			case PUSH:
				PushMsg pushMsg = (PushMsg) baseMsg;
				logger.info("phoneNum = " + pushMsg.getPhoneNum() + ", content = " + pushMsg.getContent());
				break;
			default:
				logger.info("default。。");
				break;
		}
		ReferenceCountUtil.release(baseMsg);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext arg0, BaseMsg arg1) throws Exception {
		// TODO Auto-generated method stub
		
	}
}